import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Button, message, Input } from 'antd';
import PateoTable from '../../../components/common/PateoTable';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { FormInstance } from 'antd/lib/form';
import { filterAuth } from '@/support/common';
import PropTypes from 'prop-types';
import styles from '../../../components/common/PateoTable/TableList.less';
import { PlusOutlined } from '@ant-design/icons';
import AddModal from './addModal';
import EditModal from './editModal';
import ViewPrivateKey from './viewKey';
import stylesIndex from './index.less';
import { getDicByKey } from '@/support/common';

const mapStateToProps = (state: any) => ({});
class privateKey extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();

  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      addVisible: false,
      editModalVisible: false,
      viewKey: false,
      tableData: [], //请求列表数据
      total: 0, //总数
      curPage: 1,
      pageSize: 10,
      tableLoading: false,
      tenantData: {},
      secretName: '',
      editModalData: {},
      viewKeyData: {},
    };
  }

  componentDidMount() {
    this.handleTableData();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/initData',
    });
  }
  // 获取用户列表
  handleTableData = () => {
    const { curPage, pageSize, secretName } = this.state;
    this.setState({
      tableLoading: true,
    });
    let submitData = {
      curPage,
      pageSize,
      secretName,
    };
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/secret/findpage',
        ...submitData,
      },
      callback: response => {
        if (response && response.statusCode == '0' && response.data) {
          if (response.data.list.length === 0 && response.data.pageNum > 1) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              },
            );
          } else {
            this.setState({
              tableData: response.data.list,
              total: response.data.total,
              selectedRowKeys: [],
            });
          }
        } else {
          if (response.statusCode !== '0') {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  open = () => {
    this.setState({
      addVisible: true,
    });
  };
  Edit = record => {
    this.setState({
      editModalData: {
        tenantData: [
          {
            value: record.tenantCode,
            title: record.tenantName,
          },
        ],
        ...record,
      },
      editModalVisible: true,
    });
  };
  viewKey = record => {
    this.setState({
      viewKey: true,
      viewKeyData: {
        createType: record.createType,
        secretPublic: record.secretPublic,
        secretPrivate: record.secretPrivate,
      },
    });
  };
  changeAddModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        addVisible: false,
      });
    } else {
      this.setState({
        addVisible: false,
      });
    }
  };
  changeEditModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    } else {
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    }
  };
  closeViewModal = () => {
    this.setState({
      viewKey: false,
    });
  };
  // 启用禁用
  handleChange = record => {
    if (record.secretStatus === 0) {
      this.props.dispatch({
        type: 'http/postObjWithRes',
        payload: {
          url: `/secret/disable?secretSid=${record.sid}`,
        },
        callback: response => {
          if (response && response.statusCode == '0') {
            message.success('操作成功');
            this.handleTableData();
          } else {
            // message.error(response.statusMessage);
          }
        },
      });
    } else if (record.secretStatus === 1) {
      this.props.dispatch({
        type: 'http/postObjWithRes',
        payload: {
          url: `/secret/enable?secretSid=${record.sid}`,
        },
        callback: response => {
          if (response && response.statusCode == '0') {
            message.success('操作成功');
            this.handleTableData();
          } else {
            // message.error(response.statusMessage);
          }
        },
      });
    }
  };

  handleDelete = record => {
    this.props.dispatch({
      type: 'http/postObjWithRes',
      payload: {
        url: `/secret/delete?secretSid=${record.sid}`,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };

  handleSearch = () => {
    this.handleTableData();
  };

  handleReset = () => {
    this.setState(
      {
        curPage: 1,
        pageSize: 10,
        secretName: '',
      },
      () => {
        this.handleTableData();
      },
    );
  };

  render() {
    const {
      location: { pathname = '/' },
    } = this.props;
    const {
      tableData,
      total,
      curPage,
      pageSize,
      addVisible,
      editModalVisible,
      viewKey,
      secretName,
      tenantData,
      editModalData,
      tableLoading,
      viewKeyData,
    } = this.state;

    const columns = [
      {
        title: '租户',
        dataIndex: 'tenantName',
      },
      {
        title: '密钥编码',
        dataIndex: 'secretCode',
      },
      {
        title: '密钥名称',
        dataIndex: 'secretName',
      },
      {
        title: '业务模块',
        dataIndex: 'moduleCode',
        render: (text: any, record: any) => {
          return getDicByKey(this.context.dicData, 'seretModel', text);
        },
      },
      {
        title: '生成方式',
        dataIndex: 'createType',
        render: (text: any, record: any) => {
          return record.createType === 1 ? '自动生成' : '手动生成';
        },
      },
      {
        title: '备注',
        dataIndex: 'secretDesc',
      },
      {
        title: '启用状态',
        dataIndex: 'secretStatus',
        render: (text: any, record: any) => {
          return record.secretStatus == 0 ? '已启用' : '已禁用';
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        fixed: 'right',
        width: 140,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '查看密钥',
              key: 'configList',
              auth: 'privateKey_doConfigList',
              onConfirm: () => this.viewKey(record),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'privateKey_doEdit',
              onConfirm: () => this.Edit(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'privateKey_doDel',
              Popconfirm: true,
              message: '删除后该密钥将无法使用，是否确认删除',
              onConfirm: () => this.handleDelete(record),
            },
            {
              title: record.secretStatus === 1 ? '启用' : '禁用',
              key: 'doOn',
              auth: 'privateKey_doOn',
              Popconfirm: true,
              message:
                record.secretStatus === 1 ? '是否确认启用' : '禁用后该密钥将无法使用，是否确认禁用',
              onConfirm: () => this.handleChange(record),
            },
          ];

          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current: curPage,
      pageSize: pageSize,
      total: total,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };
    const tableProps = {
      columns,
      dataSource: tableData,
      rowKey: 'sid',
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      loading: tableLoading,
      onChange: pagination => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          },
        );
      },
    };
    return (
      <div>
        <Card bordered={false}>
          <div className={stylesIndex.pateoSearch}>
            <div className={stylesIndex.searchInputStr}>
              <div className={stylesIndex.title}>密钥名称:</div>
              <Input
                placeholder="请输入密钥名称"
                value={secretName}
                onChange={e => {
                  this.setState({
                    secretName: e.target.value,
                  });
                }}
              />
            </div>

            <div className={stylesIndex.searchBtn}>
              <Button
                onClick={() => this.handleSearch()}
                type={'primary'}
                style={{ marginRight: '10px' }}
              >
                查询
              </Button>
              <Button onClick={() => this.handleReset()}>重置</Button>
            </div>
          </div>
        </Card>
        <Card className={styles.standardTable}>
          {filterAuth('privateKey_doAdd', this.context.permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.open()}
              >
                新增
              </Button>
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'role/postFetchPage', url: '/role/page' }}
            formValues={tableProps}
          />
        </Card>
        {addVisible ? (
          <AddModal tenantData={tenantData} changeAddModalVisible={this.changeAddModalVisible} />
        ) : null}
        {editModalVisible ? (
          <EditModal
            editModalData={editModalData}
            changeEditModalVisible={this.changeEditModalVisible}
          />
        ) : null}

        <ViewPrivateKey
          closeModal={this.closeViewModal}
          modalVisible={viewKey}
          viewKeyData={viewKeyData}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(privateKey);
